import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { userLogin } from "@/api/user";
import { message } from "antd";

import Cookies from 'js-cookie';
import { createBrowserHistory } from 'history'

const history = createBrowserHistory()

export const doLogin = createAsyncThunk(
    'user/login',
    async (params: any = {}) => {
        const res = await userLogin(params)
        return res.data
    }
)

const initialState = {
    token: Cookies.get('token') || '',
    userInfo: Cookies.get('userInfo')
        ?
        JSON.parse(Cookies.get('userInfo'))
        :
        {}
    ,
    role: Cookies.get('role') || ''
};

export const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {
        initUser(state, { payload }) {

        }
    },
    extraReducers: (builder) => {
        // 添加 异步 请求
        builder.addCase(doLogin.fulfilled, (state, { payload }) => {
            // action中的payload就是返回的数据
            // 返回结果 赋值给state

            if (payload.code === 200) {
                const { token, role, userInfo } = payload.data;
                Cookies.set('token', token);
                Cookies.set('role', role);
                Cookies.set('userInfo', JSON.stringify(userInfo));
                state.role = role;
                state.token = token;
                state.userInfo = userInfo;
                message.success('登录成功', 2, () => {
                    // 回到首页
                    history.replace('/dashBoard');
                    history.go(0);
                })
            }
        })
    }
});

export const {  initUser } = userSlice.actions

export default userSlice.reducer
